// 使用 packages/http 中的实现，参考 micro-frontend-main 适配 Element Plus
import { 
  createAxios, 
  download, 
  setHttpConfig,
  cryptoUtils,
} from '@tuxing/network-http';
// 导入共享Token管理器
import { microFrontendTokenManager } from '@tuxing/core-token';
import { cache } from '@tuxing/utils-base';
import { ElMessage, ElMessageBox, ElLoading, ElNotification } from 'element-plus';

import errorCode from './errorCode';

// 创建 Element Plus 适配器
const messagePluginAdapter = {
  error: (message: string) => ElMessage.error(message),
  warning: (message: string) => ElMessage.warning(message),
  info: (message: string) => ElMessage.info(message),
  success: (message: string) => ElMessage.success(message),
};

const notifyPluginAdapter = {
  error: (options: { title: string; zIndex?: number }) => 
    ElNotification.error({ title: options.title, zIndex: options.zIndex }),
  warning: (options: { title: string; zIndex?: number }) => 
    ElNotification.warning({ title: options.title, zIndex: options.zIndex }),
  info: (options: { title: string; zIndex?: number }) => 
    ElNotification.info({ title: options.title, zIndex: options.zIndex }),
  success: (options: { title: string; zIndex?: number }) => 
    ElNotification.success({ title: options.title, zIndex: options.zIndex }),
};

const dialogPluginAdapter = {
  confirm: (options: {
    header: string;
    body: string;
    cancelBtn: string;
    confirmBtn: string;
    theme: string;
    onConfirm: () => void;
    onCancel: () => void;
  }) => {
    console.log('🔧 [System-App DialogPlugin] confirm 被调用:', {
      header: options.header,
      body: options.body,
      timestamp: Date.now()
    });
    console.trace('🔧 [System-App DialogPlugin] 调用栈:');
    
    ElMessageBox.confirm(options.body, options.header, {
      confirmButtonText: options.confirmBtn,
      cancelButtonText: options.cancelBtn,
      type: options.theme as any,
    })
      .then(() => {
        console.log('🔧 [System-App DialogPlugin] 用户点击确定');
        options.onConfirm();
      })
      .catch(() => {
        console.log('🔧 [System-App DialogPlugin] 用户点击取消');
        options.onCancel?.();
      });
  },
};

const loadingPluginAdapter = (options: { text: string; attach: string; fullscreen: boolean; zIndex: number }) => {
  const loadingInstance = ElLoading.service({
    lock: options.fullscreen,
    text: '', // 不显示文本，保持统一的加载体验
    background: 'rgba(0, 0, 0, 0.7)',
  });
  
  return {
    hide: () => loadingInstance.close(),
  };
};

const userStoreAdapter = {
  get token() {
    const token = microFrontendTokenManager.getToken();
    console.log('🔑 [SystemApp Token] Retrieved token:', token ? `${token.substring(0, 20)}...` : 'null');
    return token;
  },
  async logout() {
    // 使用共享Token管理器清理所有token
    microFrontendTokenManager.clearAllTokens();
  },
};

// 使用 @tuxing/network-http 导出的 cryptoUtils
const cryptoUtilsAdapter = cryptoUtils;

// 简单的国际化适配器
const i18nAdapter = {
  global: {
    t: (key: string) => key,
  },
};

// 配置 HTTP 库
setHttpConfig({
  errorCode,
  messageOptionMerge: (message: string) => message,
  messagePlugin: messagePluginAdapter,
  notifyPlugin: notifyPluginAdapter,
  dialogPlugin: dialogPluginAdapter,
  loadingPlugin: loadingPluginAdapter as any,
  cache,
  userStore: userStoreAdapter,
  i18n: i18nAdapter as any,
  cryptoUtils: cryptoUtilsAdapter,
  // 禁用自动日期格式化，避免数组被错误处理
  formatDate: false,
});

// 统一API基础路径配置
const API_BASE_URL = import.meta.env.DEV ? '' : import.meta.env.VITE_APP_BASE_API || '';

console.log('🔧 [SystemApp Request] Environment:', import.meta.env.DEV ? 'development' : 'production');
console.log('🔧 [SystemApp Request] API_BASE_URL:', API_BASE_URL);

// 创建请求配置
const requestConfig = {
  baseURL: import.meta.env.DEV ? '/dev-api' : API_BASE_URL,
  requestOptions: {
    isJoinPrefix: false,
    urlPrefix: '',
    apiUrl: '',
    // 禁用自动日期格式化
    formatDate: false,
  },
};

console.log('🔧 [SystemApp Request] Final config:', requestConfig);

// 导出配置好的请求实例
export const request = createAxios(requestConfig);

// 导出下载函数
export { download };

// 导出默认实例
export default request;
